package com.example.myapp.Activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.CommentAdaper;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Comment;
import com.example.myapp.Model.Defaulticon;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.Password;
import com.example.myapp.Model.User;
import com.example.myapp.R;

import org.json.JSONObject;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;

public class Register extends AppCompatActivity {
 private    MyData myData;
 private    ImageView reg_back;
 private    Button  reg_go;
 private    ShapeLoadingDialog shapeLoadingDialog;
 private   EditText reg_username;
 private    EditText reg_phone;
 private    EditText reg_pwd2;
 private    EditText reg_pwd1;
 private    BmobFile neticon;
    private    EditText code;
    private TextView setcode;

    private Timer timer;
    private  int p=60;
    private String url="http://pybchat.justwen233.cn/addUser";
    private String url2="http://pybchat.justwen233.cn/addChatMsg";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: {
                    p--;
                    setcode.setText(""+p+"秒");
                    setcode.setEnabled(false);
                    setcode.setBackgroundColor(Color.parseColor("#CCCCCC"));
                    setcode.setTextColor(Color.parseColor("#FFFFFF"));//
                    if (p==0){
                        setcode.setEnabled(true);
                        setcode.setText("获取验证码");
                        setcode.setBackgroundColor(Color.parseColor("#FFC107"));
                        setcode.setTextColor(Color.parseColor("#474444"));//
                        timer.cancel();

                    }
                    Log.w("aaaa", "发送验证码成功，");
                    break;
                }
                case 1:{
                    getNeticon();
                    break;
                }
            }
        }
    };

    public void onBackPressed() {
        //此处写退向后台的处理
        finish();
    }//手机返回键
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_register);
          reg_phone = findViewById(R.id.reg__phone);
          reg_pwd1 = findViewById(R.id.reg__pwd1);
          reg_pwd2 = findViewById(R.id.reg_pwd2);
          reg_username = findViewById(R.id.reg_username);
         reg_back = findViewById(R.id.reg_back);
          reg_go = findViewById(R.id.reg_go);
        code=findViewById(R.id.code);
        setcode= findViewById(R.id.setcode);
         myData=(MyData)getApplication();
        Message message = new Message();
        message.what = 1;
        handler.sendMessage(message);
        //文本框监听开始，判断昵称是否被占用
        TextWatcher watcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Toast.makeText(getApplicationContext(), "输入之前", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Toast.makeText(getApplicationContext(), "在输入中", Toast.LENGTH_SHORT).show();
                BmobQuery<User> categoryBmobQuery = new BmobQuery<>();
                categoryBmobQuery.addWhereEqualTo("username",reg_username.getText().toString());
                categoryBmobQuery.findObjects(new FindListener<User>() {
                    @Override
                    public void done(List<User> object, BmobException e) {
                        if (e == null) {
                            if (object.size()>0){
                                Log.w("aaaa", "用户名被占用" + object);
                                Toast.makeText(Register.this, "该昵称已经被占用，请重试！", Toast.LENGTH_LONG).show();
                            }else {
                                Log.w("aaaa","用户名能用");
                            }
                        } else {
                            Log.w("aaaa", "系统出错");
                        }
                    }
                });
            }
            @Override
            public void afterTextChanged(Editable s) {



            }
        };
        reg_phone.addTextChangedListener(watcher);
        //文本框监听结束

        reg_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              finish();
            }
        });//返回按钮
        setcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMobileNO(reg_phone.getText().toString().trim())) {
                    // TODO 设置定时器
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Message message = new Message();
                            message.what = 0;
                            handler.sendMessage(message);
                        }
                    }, 1000, 2000);  // TODO 每隔一秒执行一下

                    BmobSMS.requestSMSCode(reg_phone.getText().toString().trim(), "YZM", new QueryListener<Integer>() {
                        @Override
                        public void done(Integer smsId, BmobException e) {
                            if (e == null) {
                                Toast.makeText(Register.this,  "发送验证码成功!\n", Toast.LENGTH_LONG).show();
                                Log.w("bbb", "done: "+smsId );
                            } else {
                                Toast.makeText(Register.this, "发送验证码失败：\n" + e.getErrorCode() + "-" + e.getMessage() + "\n", Toast.LENGTH_LONG).show();

                            }
                        }
                    });
                }else {
                    Toast.makeText(Register.this, "手机号格式错误，请重试！", Toast.LENGTH_LONG).show();
                }
            }

        });//发送验证码
        reg_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final   String username = reg_username.getText().toString();
                final String codes=code.getText().toString();
                final   String phone = reg_phone.getText().toString();
                final  String pwd2 = reg_pwd2.getText().toString();
                if(code.length()<1){
                    Toast.makeText(Register.this, "请输入验证码！", Toast.LENGTH_LONG).show();

                }else {
                    BmobQuery<User> categoryBmobQuery = new BmobQuery<>();
                    categoryBmobQuery.addWhereEqualTo("mobilePhoneNumber",phone);
                    categoryBmobQuery.findObjects(new FindListener<User>() {
                        @Override
                        public void done(List<User> object, BmobException e) {
                            if (e == null) {
                                if (object.size()>0){
                                    Log.w("aaaa", "手机号被占用" + object);
                                    Toast.makeText(Register.this, "该手机号已经被注册，请重试！", Toast.LENGTH_LONG).show();

                                }else {
                                    Log.w("aaaa", "手机号能用");
                                    if (reg_pwd1.getText().toString().trim().length() < 6) {
                                        Toast.makeText(Register.this, "密码不能少于6位数", Toast.LENGTH_LONG).show();
                                    } else {
                                        if (!reg_pwd1.getText().toString().equals(reg_pwd2.getText().toString())) {
                                            Toast.makeText(Register.this, "两次密码不一致，请重试", Toast.LENGTH_LONG).show();
                                        } else {
                                            openLoading();
                                            signOrLogin(phone,codes,pwd2);//注册
                                        }
                                    }
                                }
                            } else {
                                Log.w("aaaa", "系统出错请稍后重试");
                                Toast.makeText(Register.this, "系统出错请稍后重试", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }



            }
        });//注册按钮

    }
    //获取默认头像作为上传
    private void  getNeticon(){
    BmobQuery<Defaulticon> bmobQuery = new BmobQuery<Defaulticon>();
    bmobQuery.getObject("nlS2IIIO", new QueryListener<Defaulticon>() {
        @Override
        public void done(Defaulticon object,BmobException e) {
            if (e == null) {
                neticon = object.getIcon();
                Log.w("aaaa", "默认头像:"+neticon.getUrl());
            }
        }
    });
}

    private void signOrLogin(String phone,String code,String pwd) {
        final User user = new User();
        user.setUsername(reg_username.getText().toString());
        user.setMobilePhoneNumber(reg_phone.getText().toString());
        user.setMobilePhoneNumberVerified(true);//默认手机已经完成验证！
        user.setPassword(reg_pwd2.getText().toString());
        //注册默认信息
        user.setIcon(neticon);
        user.setSex(myData.getSex());
        user.setBirth(myData.getBirth());
        user.setBirthPlace(myData.getBirthPlace());
        user.setMyEamil(myData.getEmail());
        user.setShow(myData.getShow());
        user.signOrLogin(code, new SaveListener<User>() {
            @Override
            public void done(User user,BmobException e) {
                if (e == null) {
                    addChatUser(user.getObjectId(),user.getUsername(),user.getIcon().getUrl());
                    addPwd(user.getObjectId(),pwd);//记录密码
                    closeLoading();
                    //记住密码开始
                    SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                    //获取editor
                    SharedPreferences.Editor editor = sp.edit();
                    //构造数据对
                    editor.putString("phone", phone);
                    editor.putString("pwd", pwd);
                    editor.putString("pwdview", pwd);//登录页记住密码用
                    editor.putBoolean("save", true);
                    //提交数据
                    editor.commit();
                    //数据将保存到文件里
                    Toast.makeText(Register.this, "注册成功！", Toast.LENGTH_LONG).show();
                    startActivity(new Intent(Register.this, Main.class));
                } else {
                    Toast.makeText(Register.this, "验证码错误！，请重新输入"+ e.getErrorCode() + "-" + e.getMessage() + "\n", Toast.LENGTH_LONG).show();
                    closeLoading();
                }
            }
        });
    }




    // 账号密码注册
    private void signUp() {
                    final User user = new User();
                    user.setUsername(reg_username.getText().toString());
                    user.setMobilePhoneNumber(reg_phone.getText().toString());
                    user.setMobilePhoneNumberVerified(true);//默认手机已经完成验证！
                    user.setPassword(reg_pwd2.getText().toString());
                    //注册默认信息
                    user.setIcon(neticon);
                    user.setSex(myData.getSex());
                    user.setBirth(myData.getBirth());
                    user.setBirthPlace(myData.getBirthPlace());
                    user.setMyEamil(myData.getEmail());
                    user.setShow(myData.getShow());
                    user.signUp(new SaveListener<User>() {
                        public void done(User usered, BmobException e) {
                            if (e == null) {
                                Toast.makeText(Register.this, "注册成功！", Toast.LENGTH_LONG).show();
                                Log.w("aaaa", "注册成功" + usered.getUsername());
                                reg_username.setText("");
                                 reg_phone.setText("");
                                 reg_pwd1.setText("");
                                 reg_pwd2.setText("");
                                closeLoading();
                                startActivity(new Intent(Register.this,Login.class));
                                finish();

                            } else {
                                Log.w("aaaa", "注册失败:" +e.getMessage());
                            }
                        }
                    });


    }
    //添加密码记录
    private void addPwd(String userid,String pwd){
        Password password = new Password();
        User user = new User();
        user.setObjectId(userid);
        password.setPwd(pwd);
        password.setUser(user);//上传当前作者名字
        password.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Log.i("aaaa", "记录密码成功");
                } else {
                    Log.i("aaaa", "记录密码成功失败：" + e.getMessage());
                    closeLoading();
                }
            }
        });
    }
    //添加聊天服务信息
    private  void addChatUser(String objectId,String username,String icon){

        Map<String,String> map=new HashMap<String,String>();
        map.put("objectId",objectId);
        map.put("username", username);
        map.put("icon", icon);
        JSONObject params=new JSONObject(map);
        RequestQueue requestQueue2 = Volley.newRequestQueue(Register.this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.w("vivi", "onResponse: "+ response);
                adminChat("5ac31aebdc",objectId,"感谢您的使用，莆院帮欢迎您！");
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());

            }
        });
        //添加队列
        requestQueue2.add(jsonObjectRequest);
        requestQueue2.cancelAll(this);



    }
    //添加管理员发消息
    private  void adminChat(String author,String other,String content){

        Map<String,String> map=new HashMap<String,String>();
        map.put("author",author);
        map.put("other", other);
        map.put("content", content);
        JSONObject params=new JSONObject(map);
        RequestQueue requestQueue2 = Volley.newRequestQueue(Register.this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url2, params, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.w("vivi", "onResponse: "+ response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());

            }
        });
        //添加队列
        requestQueue2.add(jsonObjectRequest);
        requestQueue2.cancelAll(this);



    }




    //正则表达验证手机号
    public static boolean isMobileNO(String mobiles){
        String telRegex = "[1][3456789]\\d{9}";
        if (TextUtils.isEmpty(mobiles)){
            return false;
        }
        else return mobiles.matches(telRegex);
    }

//弹出一个进度条对话框

    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
            shapeLoadingDialog.dismiss();
    }


}